package com.zj.project.common.base

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.RecyclerView

/**
 * createTime:2021/8/3 10:19
 * auth:张继
 * des:
 */
abstract class BaseAdapter<T, VDB : ViewDataBinding>(private val layoutId: Int) :
    RecyclerView.Adapter<BaseViewHolder<VDB>>() {
    private val list: MutableList<T> by lazy {
        arrayListOf()
    }

    fun notifyData(data: T) {
        list.add(data)
        notifyDataSetChanged()
    }

    fun notifyDataPosition(data: T, position: Int) {
        list.add(position, data)
        notifyItemChanged(position)
    }

    fun notifyList(list: List<T>) {
        this.list.addAll(list)
        notifyDataSetChanged()
    }

    fun notifyIntervalList(list: List<T>) {
        val oldSize = this.list.size
        this.list.addAll(list)
        notifyItemChanged(oldSize, this.list.size)
    }

    fun notifyListPosition(list: List<T>, position: Int) {
        this.list.addAll(position, list)
        notifyItemChanged(position, this.list.size)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<VDB> {
        return BaseViewHolder(
            DataBindingUtil.inflate(LayoutInflater.from(parent.context), layoutId, parent, false)
        )
    }

    override fun onBindViewHolder(holder: BaseViewHolder<VDB>, position: Int) {
        val binding: VDB = DataBindingUtil.getBinding<VDB>(holder.itemView) as VDB
//        binding.setVariable(BR.item, list.get(position))
        binding.executePendingBindings()
        onBind(binding, holder, list[position], holder.itemView.context)
    }

    abstract fun onBind(binding: VDB, holder: BaseViewHolder<VDB>, data: T, context: Context)

    override fun getItemCount(): Int {
        return list.size
    }

}